﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DesignerHelper.Addons.TemplateConvertor;
using SpreadsheetGear;
using DesignerHelper.Main;
using WorkbookDesigner.Annotations;
using WorkbookDesigner.Main;


namespace WorkbookDesigner.Addons
{
    public partial class TemplateConvertor : Form, INotifyPropertyChanged
    {
        private string _ctpxLocation = string.Empty;
        private string _edgxLocation = string.Empty;
        private string _hwrxLocation = string.Empty;
        private string _newCtpxLocation = string.Empty;
        private TemplateConvertor(IMainWindow mw)
        {
            InitializeComponent();
            BookSet = Factory.GetWorkbookSet(System.Globalization.CultureInfo.CurrentCulture);
            BookSet.SheetsInNewWorkbook = 5;//规格组合并后的工作表页数
            BookSet.DefaultFontName = "微软雅黑";
            BookSet.DefaultFontSize = 11;
            LbwTrigger = LockBookWorker.GetWorker(BookSet);
            Mw = mw;

        }

        public event PropertyChangedEventHandler PropertyChanged;

        public string CtpxLocation
        {
            get { return _ctpxLocation; }
            private set
            {
                if (value == _ctpxLocation) return;
                _ctpxLocation = value;
                OnPropertyChanged();
            }
        }

        public string EdgxLocation
        {
            get { return _edgxLocation; }
            private set
            {
                if (value == _edgxLocation) return;
                _edgxLocation = value;
                OnPropertyChanged();
            }
        }

        public string HwrxLocation
        {
            get { return _hwrxLocation; }
            private set
            {
                if (value == _hwrxLocation) return;
                _hwrxLocation = value;
                OnPropertyChanged();
            }
        }

        public string NewCtpxLocation
        {
            get { return _newCtpxLocation; }
            private set
            {
                if (value == _newCtpxLocation) return;
                _newCtpxLocation = value;
                OnPropertyChanged(nameof(NewCtpxLocation));
            }
        }

        private static TemplateConvertor Tc { get; set; }

        private IWorkbookSet BookSet { get; set; }
        private IWorkbook CtpxNew { get; set; }

        private IWorkbook CtpxO { get; set; }
        private IWorkbook EdgxO { get; set; }
        private IWorkbook HwrxO { get; set; }

        private LockBookWorker LbwTrigger { get; }

        private IMainWindow Mw { get; set; }
        public static void GetInstance(IMainWindow mw)
        {
            if (Tc != null)
                Tc.Activate();
            else
            {
                Tc = new TemplateConvertor(mw);
                Tc.Show(mw.GetForm());
            }
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private static bool CheckDirectoryPath(params FileInfo[] fileInfos)
        {
            bool pathExists = true;
            foreach (FileInfo info in fileInfos.Where(info => info.Directory != null && !info.Directory.Exists))
            {
                pathExists = false;
                DesignerHelper.Help.MesBox.ErrorMessage($"目录 {info.Directory.FullName} 不存在，请检查路径");
                break;
            }
            return pathExists;
        }

        private static bool CheckFilePath(params string[] locations)
        {
            bool flag = true;
            foreach (string location in locations.Where(location => !System.IO.File.Exists(location)))
            {
                flag = false;
                DesignerHelper.Help.MesBox.ErrorMessage($"文件 {location} 不存在，请检查路径");
                break;
            }
            return flag;
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonConvert_Click(object sender, EventArgs e)
        {
            StartConverting();
        }

        private void buttonSelectCtpx_Click(object sender, EventArgs e)
        {
            using (openFileDialog = FileFilter.GetCtpxFileDialog())
            {
                CtpxLocation = GetFileLocation(openFileDialog);
            }
        }

        private void buttonSelectEdgx_Click(object sender, EventArgs e)
        {
            using (openFileDialog = FileFilter.GetEdgxFileDialog())
            {
                EdgxLocation = GetFileLocation(openFileDialog);
            }
        }

        private void buttonSelectHwrx_Click(object sender, EventArgs e)
        {
            using (openFileDialog = FileFilter.GetHwrxFileDialog())
            {
                HwrxLocation = GetFileLocation(openFileDialog);
            }
        }

        private void buttonSelectNewCtpx_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog saveFileDialog = FileFilter.GetNewCtpxSaveDialog())
            {
                if (saveFileDialog.ShowDialog() != DialogResult.OK)
                    return;
                NewCtpxLocation = saveFileDialog.FileName;
            }
        }

        private bool CheckDirectoryPath(params string[] directories)
        {
            bool flag = true;
            foreach (FileInfo fi in directories.Select(directory => new FileInfo(directory)).Where(fi => fi.Directory != null && !fi.Directory.Exists))
            {
                flag = false;
                DesignerHelper.Help.MesBox.ErrorMessage("目录 " + fi.Directory.FullName + " 不存在,请检查路径");
                break;
            }
            return flag;

        }

        private string GetFileLocation(OpenFileDialog dia)
        {
            DialogResult result = dia.ShowDialog();
            switch (result)
            {
                case DialogResult.OK:
                    return dia.FileNames[0];
                default:
                    return null;
            }
        }

        private void MakePreparation()
        {
            CtpxNew = BookSet.Workbooks.Add();
            CtpxO = BookSet.Workbooks.Open(CtpxLocation);
            HwrxO = BookSet.Workbooks.Open(HwrxLocation);
            EdgxO = BookSet.Workbooks.Open(EdgxLocation);
        }

        private bool SaveNewCtpx()
        {
            if (!CheckDirectoryPath(new FileInfo(NewCtpxLocation)))
                return false;
            LbwTrigger.DoWork(() =>
            {
                CtpxNew.SaveAs(NewCtpxLocation, FileFormat.OpenXMLWorkbook);
                DesignerHelper.Help.MesBox.InfoMessage("合并文件成功，文件放置在 " + NewCtpxLocation);
            });
            return true;
        }

        private void StartConverting()
        {
            progressBar.Value = 0;
            BookSet.Workbooks.Close();
            if (!CheckFilePath(CtpxLocation, HwrxLocation, EdgxLocation))
                return;

            MakePreparation();
            backgroundWorker.RunWorkerAsync();
        }

        private void TemplateConvertor_FormClosed(object sender, FormClosedEventArgs e)
        {
            Tc = null;
        }

        private void TemplateConvertor_Load(object sender, EventArgs e)
        {
            textBoxNewCtpxLocation.DataBindings.Add(new Binding("Text", this, "NewCtpxLocation", false, DataSourceUpdateMode.OnPropertyChanged));
            textBoxCtpxLocation.DataBindings.Add(new Binding("Text", this, "CtpxLocation", false, DataSourceUpdateMode.OnPropertyChanged));
            textBoxEdgxLocation.DataBindings.Add(new Binding("Text", this, "EdgxLocation", false, DataSourceUpdateMode.OnPropertyChanged));
            textBoxHwrxLocation.DataBindings.Add(new Binding("Text", this, "HwrxLocation", false, DataSourceUpdateMode.OnPropertyChanged));
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<FileConvertor> worklist = new List<FileConvertor>(3);
            LbwTrigger.DoWork(() =>
            {
                try
                {
                    worklist.AddRange(new FileConvertor[]{
                        new CtpxConvertor(CtpxO, CtpxNew),
                        new EdgxConvertor(EdgxO, CtpxNew),
                        new HwrxConvertor(HwrxO, CtpxNew),
                    });
                    Action updateBar = () => progressBar.PerformStep();
                    foreach (FileConvertor convertor in worklist)
                    {
                        convertor.BeginConvert();
                        progressBar.BeginInvoke(updateBar);

                    }
                    bool successed = SaveNewCtpx();
                    e.Result = successed;
                    BookSet.Workbooks.Close();
                    progressBar.BeginInvoke(updateBar);

                }
                catch (Exception ex)
                {
                    DesignerHelper.Help.MesBox.ErrorMessage(ex);
                }
            });

        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((bool)e.Result)
                Mw.FileOperator.OpenFile(NewCtpxLocation);

        }
    }
}
